/**
 * 把学生添加到某个年度里
 * 
 * /xingzheng/topic/addstudent
 * 
 * 参数：
 * year_id Number
 * user_name String
 */

const Year = require('../../../models/years')
const Studens = require('../../../models/users')
const Research_Student = require('../../../models/researchTopicStudents')
const utils = require('../../../utils/index')
const $ = require('../../../utils/common')

const insert_student_into_year = async function (req, res) {
    try {
        // 判断该年度是否存在
        if (!'year_id' in req.body) {
            $.sendMessage(res, 1015, '缺少参数 year_id')
            return
        }

        
        // 判断user_name是否符合要求的格式
        if (!'user_name' in req.body) {
            $.sendMessage(res, 1015, '缺少参数 user_name')
            return
        }


        // 是否字符串
        if (typeof req.body.user_name !== 'string') {
            $.sendMessage(res, 1015, '参数格式错误 user_name')
            return
        }


        // 判断年度是否存在
        let resultOfYearQuery = await Year.findOne({
            where: {
                id: req.body.year_id,
                type: 0
            }
        })
        if (resultOfYearQuery === null) {
            $.sendMessage(res, 1015, '年度不存在')
            return
        }


        // 处理学生的学号格式, 去重
        let arr = req.body.user_name.split(',')
        let set = new Set(arr)
        let insertStudentList = [...set]


        // 查询所有学生
        const resultOfStudentsQuery = await Studens.findAll({
            where: {
                user_role: 'student',
                user_status: 1
            },
            attributes: ['user_name']
        })


        // 查询学生与要插入的学生去并集
        let queryStudentList = resultOfStudentsQuery
        let unionSet = [] // 要插入实习年度的学生学号
        for (let item of insertStudentList) {
            if (queryStudentList.findIndex(i => i.dataValues.user_name == item) !== -1) {
                unionSet.push(item)
            }
        }
        unionSet = unionSet.map(item => {
            return {
                student_year: req.body.year_id,
                student_user_name: item
            }
        })

        // 批量插入学生
        let resultOfBulkCreate = await Research_Student.bulkCreate(
            unionSet,
            {updateOnDuplicate:["student_user_name", "student_year"]}
        )

        res.json({
            code: 200,
            result: resultOfBulkCreate
        })
        

        // 日志
        utils.create_a_log(req, '年度学生', '添加学生至入所年度')
    }
    catch(error) {
        res.json({
            code: 0000,
            message: '抓到异常',
            error: 'error' + error
        })

        utils.create_a_log(req, '年度学生', '添加学生', '失败')
    }
}
    
module.exports = insert_student_into_year